package com.dictionary.cn.core.dictionaryservice.impl;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.springframework.context.annotation.Scope;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.stereotype.Service;

import com.dictionary.cn.core.DictionaryService;
import com.dictionary.cn.core.FilterProperty;
import com.dictionary.cn.core.dictionaryservice.base.BaseDictionaryService;
import com.dictionary.cn.core.dictionaryservice.dcitionarybean.TypeDictionary;

@Service("typeDictionaryService")
@Scope("prototype")
public class TypeDictionaryServiceImpl extends BaseDictionaryService<TypeDictionary> implements DictionaryService<TypeDictionary>{
    
    /**
     * 字典缓存
     * <type,<key,dictioanry>>
     */
    private Map<String, TypeDictionary> cache ;
    
    private static final String TYPE = "#TYPE#";
    /**
     * 查询的字典sql
     */
    private String typeSql = "SELECT t.key, t.value, t.disabled FROM common_dictionary t where t.type = '"+ TYPE + "'";

    public void flush() {
        load(this.type, this.param);
    }

    public List<TypeDictionary> getAll(FilterProperty<TypeDictionary> filterProperty) {
        
        if(filterProperty == null){
            return new ArrayList<TypeDictionary>(this.cache.values());
        }else{
           List<TypeDictionary> resultDicList = new ArrayList<TypeDictionary>();
           for(TypeDictionary dic : this.cache.values()){
               if(filterProperty.filter(dic)){
                   resultDicList.add(dic);
               }
           }
           return resultDicList;
        }
    }

    public void load(String type, String param){
        this.param = param;
        this.type = type;
        if(StringUtils.isBlank(param)){
            throw new RuntimeException("字典类型参数不能为空");
        }
        
        List<TypeDictionary> list = this.jdbcTemplate.query(this.typeSql.replace(TYPE, param), BeanPropertyRowMapper.newInstance(this.getRowMapperClass()));
        if(list == null){
            list = new ArrayList<TypeDictionary>();
        }
        
        Map<String, TypeDictionary> dics = new LinkedHashMap<String, TypeDictionary>(list.size());
        for(TypeDictionary dic : list){
            
            if(dic.getKey() == null){
                throw new RuntimeException("字典类型【" + this.type + "】 有的key为空");
            }
            dics.put(dic.getKey(), dic);
        }
        this.cache = dics;
    }

    public TypeDictionary getDicByKey(String key) {
        return this.cache.get(key);
    }

    public List<TypeDictionary> getChildren(String parent,
            FilterProperty<TypeDictionary> filterProperty) {
        throw new RuntimeException(this.getClass() + "not has children!!");
    }

}
